package com.mall.common.template.method;

import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.mall.common.CommonSetting;
import com.mall.common.util.CommonSettingUtils;

import freemarker.template.SimpleScalar;
import freemarker.template.TemplateMethodModel;

/**
 * 处理货币精度标签
 * @author zhenglong
 *
 */
@Repository
public class CurrencyMethod implements TemplateMethodModel {

    @SuppressWarnings("rawtypes")
    public Object exec(List arguments) {
        if (arguments != null && !arguments.isEmpty() && arguments.get(0) != null &&
                StringUtils.isNotEmpty(arguments.get(0).toString())) {
            boolean flag = false;
            boolean flag1 = false;
            if (arguments.size() == 2) {
                if (arguments.get(1) != null)
                    flag = Boolean.valueOf(arguments.get(1).toString()).booleanValue();
            } else{
                if (arguments.size() > 2) {
                    if (arguments.get(1) != null)
                        flag = Boolean.valueOf(arguments.get(1).toString()).booleanValue();
                    if (arguments.get(2) != null)
                        flag1 = Boolean.valueOf(arguments.get(2).toString()).booleanValue();
                }
            }
            CommonSetting setting = CommonSettingUtils.get();
            BigDecimal bigdecimal = new BigDecimal(arguments.get(0).toString());
            String s = setting.setScale(bigdecimal).toString();
            if (flag)
                s = (new StringBuilder(String.valueOf(setting.getCurrencySign()))).append(s).toString();
            if (flag1)
                s = (new StringBuilder(String.valueOf(s))).append(setting.getCurrencyUnit()).toString();
            return new SimpleScalar(s);
        } else {
            return null;
        }
    }
}
